package main

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
)

func _query(context *gin.Context) {

	user := context.Query("user")
	fmt.Println(user)

	userArray := context.QueryArray("user") //string类型切片
	fmt.Println(userArray)

	userMap := context.QueryMap("user") //map   ?user[id]=1&user[name]=xxx
	fmt.Println(userMap)

	query, b := context.GetQuery("user")
	if !b {
		fmt.Println("空参数")
	} else {
		fmt.Print(query)
	}
}

func _param(context *gin.Context) {
	context.Param("user_id")
	context.Param("book_id")
}

func _form(context *gin.Context) {
	context.PostForm("form")
}

func bindJson(context *gin.Context, obj any) (err error) {
	body, _ := context.GetRawData()
	contentType := context.GetHeader("Content-Type")
	switch contentType {
	case "application/json":
		err := json.Unmarshal(body, &obj)
		if err != nil {
			fmt.Println(err.Error())
			return err
		}
	}
	return nil
}

func _raw(context *gin.Context) {
	type User struct {
		Name string `json:"name" `
		Age  int    `json:"age"`
	}
	bindJson(context, User{})
}

func main() {
	router := gin.Default()

	router.GET("/query", _query)
	router.GET("/param/:user_id", _param)
	router.GET("/param/:user_id/:book_id", _param)
	router.POST("/form", _form)
	router.POST("/raw", _raw)

	router.Run(":8080")
}
